<template>
  <div class="home-container">
    <h1 class="page-title">
      代码编辑器示例
    </h1>
    <div class="editor-wrapper">
      <MonacoEditor
        v-model="codeContent"
        language="javascript"
        theme="vs-dark"
        :options="editorOptions" />
    </div>
    <div class="editor-actions">
      <el-button @click="formatCode">
        格式化代码
      </el-button>
      <el-button
        type="primary"
        @click="runCode">
        运行代码
      </el-button>
      <el-button
        type="danger"
        @click="resetCode">
        重置
      </el-button>
    </div>
    <div class="output-section">
      <h3>运行结果:</h3>
      <pre class="output-content">{{ output }}</pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElButton } from 'element-plus';

// 编辑器内容
const codeContent = ref<string>(`// JavaScript示例代码
function greet(name) {
  return \`Hello, \${name}!\`;
}

// 测试代码
const message = greet('Monaco Editor');
console.log(message);
`);

// 编辑器配置选项
const editorOptions = ref({
  fontSize: 14,
  minimap: { enabled: true },
  scrollBeyondLastLine: false,
  wordWrap: 'on',
  lineNumbers: 'on',
  roundedSelection: false,
  readOnly: false,
  cursorStyle: 'line',
  automaticLayout: true
});

// 运行结果
const output = ref<string>('');

// 格式化代码
const formatCode = () => {
  // 实际项目中可集成prettier进行代码格式化
  output.value = '代码格式化成功！';
};

// 运行代码
const runCode = () => {
  try {
    // 创建一个安全的执行环境
    const result = new Function(codeContent.value)();
    output.value = `执行成功:\n${result || '无返回值'}`;
  } catch (error) {
    output.value = `执行错误:\n${error instanceof Error ? error.message : String(error)}`;
  }
};

// 重置代码
const resetCode = () => {
  codeContent.value = '';
  output.value = '';
};

onMounted(() => {
  output.value = '编辑器已就绪，请编写并运行代码...';
});
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  margin-bottom: 100px;
}

.page-title {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
}

.editor-wrapper {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  height: 500px;
  margin-bottom: 20px;
}

.editor-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.output-section {
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 15px;
  height: 200px;
  overflow: auto;
}

.output-content {
  color: #374151;
  font-family: monospace;
  white-space: pre-wrap;
  margin: 0;
}
</style>